<!--货品类型-->
<template>
    <el-form :model="typeform" ref="typeref" style="display: flex; align-items: center;" >
        <!-- 组织输入 -->
        <el-form-item label="部门:" prop="Department_code" style="margin-bottom: 0; margin-right: 15px;">
            <el-input
            v-model="typeform.Department_code"
            placeholder="请输入部门名称/编号"
            style="width: 180px;"
            ></el-input>
        </el-form-item>
        
        <!-- 状态选择 -->
        <el-form-item label="状态:" prop="Department_status" style="margin-bottom: 0; margin-right: 15px;">
            <el-select 
            v-model="typeform.Department_status" 
            style="width: 180px;"
            placeholder="请选择"
            >
            <el-option label="启用" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>
            </el-select>
        </el-form-item>
        
        <!-- 按钮组 -->
        <el-form-item style="margin-bottom: 0;">
            <el-button @click="Reset()">重置</el-button>
            <el-button type="success" @click="Search()">查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;margin: 5px 0 5px 0;">
        <el-button type="success" @click="drawer = true">添加</el-button>
    </div>
    <!--表格-->
    <el-table :data="typedata" style="margin-top: 10px;" row-key="department_id" default-expand-all :tree-props="{ children: 'children'}" @selection-change="SelectChange">
        <el-table-column type="index" label="序号" width="70"></el-table-column>
        <el-table-column prop="department_code" label="部门编号"></el-table-column>
        <el-table-column prop="department_name" label="部门名称"></el-table-column>
        <el-table-column prop="department_sort" label="排序"></el-table-column>
        <el-table-column prop="department_status" label="状态">
        <!-- 状态显示转换 -->
        <template #default="scope">
            {{ scope.row.department_status === 0 ? '启用' : '禁用' }}
        </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="success" text="编辑" @click="ShowUpdate(scope.row.department_id)">编辑</el-button>
                <el-button type="danger" text="删除" @click="ShowDelete(scope.row.department_id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

     <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

        <!--添加抽屉-->
        <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">添加</h4>
        </template>
        <template #default>
            <el-form :model="addform" ref="addformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-form-item label="上级分类" prop="pid">
                    <el-tree-select
                        v-model="addform.department_parentid"
                        :data="Parentclassification"
                        :props="{
                            value: 'department_id',
                            label: 'department_name',
                            children: 'children'
                        }"
                        default-expand-all
                    />
                </el-form-item>
                <el-form-item label="组织编号" prop="sort">
                    <el-input placeholder="自动获取系统编号" disabled v-model="addform.department_code"></el-input>
                </el-form-item>
                <el-form-item label="组织名称" prop="department_name">  <!-- 添加prop -->
                    <el-input placeholder="请输入" v-model="addform.department_name"></el-input>
                </el-form-item>
                
                <el-form-item label="排序" prop="department_sort">  <!-- 添加prop -->
                    <el-input placeholder="请输入" v-model.number="addform.department_sort"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="addform.department_status">
                        <el-radio :value="0">启用</el-radio>
                        <el-radio :value="1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入" v-model="addform.remark"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="Add">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!--修改抽屉-->
    <el-drawer v-model="drawer2">
        <template #header>
            <h4 style="text-align: left;">修改</h4>
        </template>
        <el-form :model="updateform" ref="updateformref" :rules="rules" label-width="auto" style="text-align: left;">
            <el-form-item label="上级分类" prop="pid">
                    <el-tree-select
                        v-model="updateform.department_parentid"
                        :data="Parentclassification"
                        :props="{
                            value: 'department_id',
                            label: 'department_name',
                            children: 'children'
                        }"
                        default-expand-all
                    />
                </el-form-item>
                <el-form-item label="组织编号" prop="sort">
                    <el-input placeholder="自动获取系统编号" disabled v-model="updateform.department_code"></el-input>
                </el-form-item>
                <el-form-item label="组织名称" prop="department_name">  <!-- 添加prop -->
                    <el-input placeholder="请输入" v-model="updateform.department_name"></el-input>
                </el-form-item>
                
                <el-form-item label="排序" prop="department_sort">  <!-- 添加prop -->
                    <el-input placeholder="请输入" v-model.number="updateform.department_sort"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="updateform.department_status">
                        <el-radio :value="0">启用</el-radio>
                        <el-radio :value="1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入" v-model="updateform.remark"></el-input>
                </el-form-item>
            </el-form>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer2 = false">取消</el-button>
                <el-button type="primary" @click="Update">确定</el-button>
            </div>
        </template>
    </el-drawer>

     <!--删除模态框-->
     <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import {ref,reactive,onMounted } from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import * as XLSX from 'xlsx';
export default {
setup()
    {
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));
        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //当前codeid
        const typeid=ref(0);

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //#region 查询
        //表单数据
        const typeref=ref("");
        const typeform=reactive({
            Department_code:"",
            Department_status:null
        })
        //表格数据
        const typedata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        //重置
        function Reset(){
            // 使用正确的表单引用 typeref
            typeref.value.resetFields();
            // 同时重置后重新加载数据
            All();
        }

        //查询
        function Search() {
            currentPage.value = 1;
            All();
        }

        // 将扁平数据转换为树状结构的函数，同时保留所有相关节点及其父节点
        function convertToTree(data) {
        const map = {};
        data.forEach(item => {
            map[item.department_id] = { ...item, children: [] }; // 使用小写
        });
        
        const tree = [];
        data.forEach(item => {
            const node = map[item.department_id];
            if (item.department_parentid === 0) { // 使用小写
            tree.push(node);
            } else {
            const parent = map[item.department_parentid]; // 使用小写
            if (parent) parent.children.push(node);
            }
        });
        return tree;
        }


        //查询数据
        function All(){
            http.get("/Department/GetDepartmentFenYe", {
            params: {
                CurrentPage: currentPage.value,
                Department_code:typeform.Department_code,
                Department_name: typeform.Department_code,
                Department_status: typeform.Department_status
                // 根据需要添加其他参数
            }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0 && currentPage.value==1) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    create_time: formatDateTime(new Date(item.create_time)),
                    type_status: item.type_status === 0 ? '启用' : '禁用'
                }));
                typedata.value = convertToTree(Data);//转为树状展示
            }).catch(err => {
                console.log(err)
            })
        }
        const Parentclassification = ref([]);

        //上级分类查询
        function ParentclassificationInquire(){
            http.get("/Department/GetDepartments").then(res => {
                const defaultOption = {
                    department_id: 0,
                    department_name: "最高层级",
                };
                Parentclassification.value = [defaultOption, ...res.data];
                console.log("Parentclassification:", Parentclassification.value); // 调试用
                
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }

        //#endregion

         //#region 删除

            //删除模态框
            const DeleteialogVisible=ref(false);
            //删除模态框
            function ShowDelete(id){
                typeid.value=id;
                DeleteialogVisible.value=true;
            }
            async function Delete() {
                try {
                    // 使用 await 获取 http.put 的返回值
                    const res = await http.put(`/Department/DeleteDepartment?id=${typeid.value}`);

                    // 检查后端返回的 code
                    if (res.data && res.data.code === 1) {
                        ElMessage.success(res.data.message || '删除成功');
                        All(); // 刷新列表
                    } else if (res.data && res.data.code === 0) {
                        ElMessageBox.alert(res.data.message || '删除失败：该岗位已被其他单据引用，无法删除', '删除失败', {
                            type: 'error',
                            confirmButtonText: '确定'
                        });
                    } else if (res.data && res.data.code === -1) {
                        ElMessage.warning(res.data.message || '岗位不存在或已被删除');
                        All(); // 刷新列表
                    } else {
                        ElMessage.error('响应格式错误或未知成功状态: ' + (res.data?.message || ''));
                    }
                    DeleteialogVisible.value=false;
                } catch (err) {
                    // 捕获到错误，说明 HTTP 状态码是 4xx 或 5xx
                    console.error("删除部门请求失败:", err);
                    // 检查错误响应体中是否包含后端返回的详细信息
                    if (err.response && err.response.data) {
                        const errorData = err.response.data;
                        if (errorData.code === 0) {
                            ElMessageBox.alert(errorData.message || '删除失败：该岗位已被其他单据引用，无法删除', '删除失败', {
                                type: 'warning',
                                confirmButtonText: '确定'
                            });
                        } else if (errorData.code === -1) {
                            ElMessage.warning(errorData.message || '岗位不存在或已被删除');
                            All(); // 刷新列表
                        } else {
                            ElMessage.error('服务器错误: ' + (errorData.message || '删除请求失败'));
                        }
                    } else {
                        ElMessage.error('删除请求失败: ' + (err.message || '网络错误或服务器无响应'));
                    }
                    DeleteialogVisible.value=false;
                }
            }

        //#endregion

        //挂载
        onMounted(() => {
            All();
            ParentclassificationInquire()
        });

        const drawer = ref(false);
        const drawer2 = ref(false);
        
        const addformref = ref("");

        const addform = reactive({
            department_code:"",
            department_parentid:0,
            department_name:"",
            department_sort:1,
            department_status: 0,
            remark: ""
        })

        // 添加
        async function Add() {
            try {
                // 先进行表单验证
                const valid = await addformref.value.validate();
                if (!valid) return;
                    // 获取自动生成编号 部门类型11
                    const GeneratedCode = async () => {
                        const res = await http.get("/CodeRule/GeneratedCode?id=11");
                        addform.department_code = res.data;
                    };
                    // 首先执行生成编号
                    await GeneratedCode();

                    //添加
                    addformref.value.validate((valid) => {
                    if (valid) {
                        //添加数据
                        const adddata = {
                            department_code:addform.department_code,
                            department_parentid:addform.department_parentid,
                            department_name:addform.department_name,
                            department_sort:addform.department_sort,
                            department_status:addform.department_status,
                            remark:addform.remark,

                        }

                        http.post("/Department/AddDepartment",adddata)
                        .then(res => {
                            if (res.data> 0) {
                                ElMessage({
                                    message: '添加成功.',
                                    type: 'success',
                                })
                                All();
                                //清除表单
                                addformref.value?.resetFields();
                                ParentclassificationInquire();
                                drawer.value=false;
                            }
                        }).catch(err => {
                            console.log(err);
                        })
                    }
                })
            } catch (err) {
                ElMessage({
                    message: '请填写必要的信息.',
                    type: 'error',
                });
            }
        }

        const updateformref=ref("");
        const updateform = reactive({
            department_id:"",
            department_code:"",
            department_parentid:0,
            department_name:"",
            department_sort:1,
            department_status: 0,
            remark: ""
        })
        //显示修改
        function ShowUpdate(id){
            drawer2.value=true;
            typeid.value=id;
            //根据当前id查询信息
            http.get("/Department/GetDepartmentID?id="+id)
            .then(res=>{
                updateform.department_id=id;
                updateform.department_code=res.data.department_code;
                updateform.department_parentid=res.data.department_parentid;
                updateform.department_name=res.data.department_name;
                updateform.department_sort=res.data.department_sort;
                updateform.department_status=res.data.department_status;
                updateform.remark=res.data.remark;

                console.log("ID查询", updateform); // 调试用
            }).catch(err=>{
                console.log(err);
            })
        }
        //修改
        function Update(){
                // 先验证表单
            updateformref.value.validate((valid) => {
                if (!valid) {
                    ElMessage.error('请填写必填项');
                    return;
                }
                //修改数据
                const updatedata ={
                    department_id:updateform.department_id,
                    department_parentid: updateform.department_parentid,
                    department_name: updateform.department_name,
                    department_sort: updateform.department_sort,
                    department_status: updateform.department_status,
                    remark: updateform.remark,
                }
                http.put("/Department/UpdateDepartment",updatedata)
                .then(res=>{
                    if(res.data>0){
                        ElMessage({
                            message: '修改成功.',
                            type: 'success',
                        })
                        All();
                        ParentclassificationInquire();
                        drawer2.value=false;
                    }
                }).catch(err=>{
                    console.log(err);
                })
            })
        }

            // 添加验证规则
            const rules = reactive({
                department_name: [
                    { required: true, message: '组织名称不能为空', trigger: 'blur' }
                ],
                department_sort: [
                    { required: true, message: '排序不能为空', trigger: 'blur' },
                    { type: 'number', message: '排序必须为数字值' }
                ]
            });


        return{
            rules,
            Update,
            ShowUpdate,
            updateform,
            updateformref,
            drawer2,
            addformref,
            Add,
            Parentclassification,
            addform,
            drawer,
            user,
            formatDateTime,
            typeref,
            typeform,
            typedata,
            rows,
            currentPage,
            dateFormat,
            Reset,
            Search,
            All,
            handlePageChange,
            convertToTree,
            typeid,
            DeleteialogVisible,
            Delete,
            ShowDelete,
            selectdata,
            SelectChange,
        }
    }
}
</script>

<style scoped>

</style>